package com.chenqi.community.controller;

import com.chenqi.community.entity.Comment;
import com.chenqi.community.entity.Post;
import com.chenqi.community.entity.User;
import com.chenqi.community.service.CommentService;
import com.chenqi.community.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * @author Ardai
 */
@Controller
//@RequestMapping("/community")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private PostService postService;

    /**
     * 添加评论
     * @param comment
     * @param modelAndView
     * @return
     */

    @PostMapping("/addComment")
    public ModelAndView addComment(Comment comment,Integer pid ,ModelAndView modelAndView, HttpSession session) {
        User user = (User) session.getAttribute("user");
        comment.setUserId(user.getId());
        comment.setPostId(pid);
        commentService.addComment(comment);
        //添加评论之后，应对帖子信息更新
        Post post = postService.findPostById(pid);
        Integer count = commentService.findCommentsCount(pid);
        post.setComments(count);
        postService.editPostInfo(post);
        //因为没有使用局部刷新,防止留言以后对浏览次数的刷新,返回时附加一个值进行判断
        modelAndView.setViewName("redirect:/post?pid="+pid+"&noView=1");
        return modelAndView;
    }
}
